package cn.dw.service.impl;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import cn.dw.dao.WeChatDao;
import cn.dw.domain.TemplateData;
import cn.dw.domain.WxTemplate;
import cn.dw.service.WeChatService;
import cn.dw.web.servlet.TokenThread;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

public class WeChatServiceImpl implements WeChatService {
	private WeChatDao wcd;

	public WeChatDao getWcd() {
		return this.wcd;
	}

	public void setWcd(WeChatDao wcd) {
		this.wcd = wcd;
	}

	public class MyX509TrustManager implements X509TrustManager {
		public MyX509TrustManager() {
		}

		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}
	}

	public JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
		JSONObject jsonObject = null;
		try {
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new SecureRandom());

			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
			conn.setSSLSocketFactory(ssf);

			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);

			conn.setRequestMethod(requestMethod);
			if (outputStr != null) {
				OutputStream outputStream = conn.getOutputStream();

				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}
			InputStream inputStream = conn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str = null;
			StringBuffer buffer = new StringBuffer();
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			conn.disconnect();
			jsonObject = JSONObject.fromObject(buffer.toString());
		} catch (ConnectException ce) {
			System.out.println("连接超时");
		} catch (Exception e) {
			System.out.println("https请求异常");
		}
		return jsonObject;
	}

	public String menuDelete(String accessToken, String menu_urldel) {
		String errmsg = "";
		String requestUrl = menu_urldel.replace("ACCESS_TOKEN", accessToken);
		JSONObject jsonObject = httpsRequest(requestUrl, "GET", null);
		if (jsonObject != null) {
			try {
				errmsg = jsonObject.getString("errcode") + jsonObject.getString("errmsg");
			} catch (JSONException e) {
				errmsg = "";
			}
		}
		return errmsg;
	}

	public String menuCreate(String accessToken, String menu_url) {
		String errmsg = "";
		String requestUrl = menu_url.replace("ACCESS_TOKEN", accessToken);

		String outputStr = "{\"button\": [{\"name\":\"学生\",\"sub_button\":[{\"type\": \"view\",\"name\": \"查看在线教师信息\",\"key\": \"list\",\"url\": \"http://wechatest00001.51vip.biz/math_app/WeChat/teacherlist.html\"}]}"
				+ ",{\"name\":\"教师\",\"sub_button\":[{\"type\": \"view\",\"name\": \"注册\",\"key\": \"regist\",\"url\":"
				+ " \"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3542023ee690ee77&redirect_uri=http%3a%2f%2fwechatest00001.51vip.biz%2fmath_app%2fWeChat%2fMlogin.html&response_type=code&scope=snsapi_base&state=123#wechat_redirect\"},"
				+ "{\"type\": \"view\",\"name\": \"组长设置\",\"key\": \"messageset\",\"url\""
				+ ": \"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3542023ee690ee77&redirect_uri=http%3a%2f%2fwechatest00001.51vip.biz%2fmath_app%2fWeChat%2fMessageSet.html&response_type=code&scope=snsapi_base&state=123#wechat_redirect\"},"
				+ "{\"type\": \"view\",\"name\": \"我的信息\",\"key\": \"mymessage\",\"url\""
				+ ": \"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3542023ee690ee77&redirect_uri=http%3A%2F%2Fwechatest00001.51vip.biz%2Fmath_app%2FWeChat%2FMyMessage.html&response_type=code&scope=snsapi_base&state=123#wechat_redirect\"},"
				+ "{\"type\": \"view\",\"name\": \"签到\",\"key\": \"signin\",\"url\""
				+ ": \"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3542023ee690ee77&redirect_uri=http%3a%2f%2fwechatest00001.51vip.biz%2fmath_app%2fWeChat%2flogin_in%26out.html%3fifin%3d1&response_type=code&scope=snsapi_base&state=123#wechat_redirect\"},{\"type\":\"view\",\"name\":\"签出\",\"key\":\"signout\",\"url\": \"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3542023ee690ee77&redirect_uri=http%3a%2f%2fwechatest00001.51vip.biz%2fmath_app%2fWeChat%2flogin_in%26out.html%3fifin%3d0&response_type=code&scope=snsapi_base&state=123#wechat_redirect\"}]}]}";

		System.out.println("创建菜单！！！！");
		JSONObject jsonObject = httpsRequest(requestUrl, "POST", outputStr);
		if (jsonObject != null) {
			try {
				errmsg = jsonObject.getString("errcode") + jsonObject.getString("errmsg");
			} catch (JSONException e) {
				errmsg = "11";
			}
		}
		System.out.println("input menuCreate errmsg = " + errmsg);
		return errmsg;
	}

	public void send_template_message(String openId, String peoplename, String checkInfoId) {
		String accessToken = TokenThread.accessToken.getAccessToken();

		String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
		WxTemplate temp = new WxTemplate();
		temp.setUrl(
				"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx3542023ee690ee77&redirect_uri=http%3a%2f%2fwechatest00001.51vip.biz%2fmath_app%2fWeChat%2fInspection.html%3fcheckInfoId%3d"
						+

						checkInfoId + "&response_type=code&scope=snsapi_base&state=123#wechat_redirect");
		temp.setTouser(openId);
		temp.setTopcolor("#000000");
		temp.setTemplate_id("vA0_ET4wxScR4GnUdtHkmyKEdITkW_Eg92QSplGoJVo");
		Map<String, TemplateData> m = new HashMap<>();
		TemplateData first = new TemplateData();
		first.setColor("#000000");
		first.setValue("查岗信息");
		m.put("first", first);
		TemplateData people = new TemplateData();
		people.setColor("#000000");
		people.setValue(peoplename);
		m.put("people", people);

		temp.setData(m);
		String jsonString = JSONObject.fromObject(temp).toString();
		JSONObject jsonObject = httpsRequest(url, "POST", jsonString);
		System.out.println(jsonObject);
		String result = null;
		if ((jsonObject != null) && (jsonObject.getInt("errcode") != 0)) {
			result = jsonObject.getString("errcode") + jsonObject.getString("errmsg");
		}
		System.out.println(result);
	}

	@SuppressWarnings("unused")
	public String getTicket(String ticketurl) {
		String errmsg = "";
		String ticket = "";
		JSONObject jsonObject = httpsRequest(ticketurl, "GET", null);
		if (jsonObject != null) {
			try {
				ticket = jsonObject.getString("ticket");
				errmsg = jsonObject.getString("errcode") + jsonObject.getString("errmsg");
			} catch (JSONException e) {
				errmsg = "";
			}
		}
		return ticket;
	}

	@SuppressWarnings("unused")
	public String getOpenId(String codeurl) {
		String errmsg = "";
		String openid = "";
		JSONObject jsonObject = httpsRequest(codeurl, "GET", null);
		if (jsonObject != null) {
			try {
				openid = jsonObject.getString("openid");
				errmsg = jsonObject.getString("errcode") + jsonObject.getString("errmsg");
			} catch (JSONException e) {
				errmsg = "";
			}
		}
		return openid;
	}
}
